package com.supermarket.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.supermarket.product.domain.ProductCategories;
import com.supermarket.product.domain.ProductGoods;
import com.supermarket.product.domain.dto.ProductCategoriesDto;
import com.supermarket.product.domain.vo.CategoryProductPageVO;
import com.supermarket.product.mapper.ProductCategoriesMapper;
import com.supermarket.product.service.IProductCategoriesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品分类业务层
 *
 * @author
 * @date
 */
@Service
public class ProductCategoriesServiceImpl extends ServiceImpl<ProductCategoriesMapper, ProductCategories> implements IProductCategoriesService
{
    @Autowired
    private ProductCategoriesMapper productCategoriesMapper;

    /**
     * 查询商品分类
     *
     * @param id 商品分类主键
     * @return 商品分类
     */
    @Override
    public ProductCategories selectProductCategoriesById(Integer id)
    {
        return productCategoriesMapper.selectProductCategoriesById(id);
    }

    /**
     * 查询商品分类列表
     *
     * @param productCategories 商品分类
     * @return 商品分类
     */
    @Override
    public List<ProductCategories> selectProductCategoriesList(ProductCategories productCategories)
    {
        List<ProductCategories> list = productCategoriesMapper.listProductCategories(productCategories.getId(),productCategories.getParentCategoryId());
        return list;
    }

    /**
     * 新增商品分类
     *
     * @param productCategories 商品分类
     * @return 结果
     */
    @Override
    public void insertProductCategories(ProductCategories productCategories)
    {
        if(productCategories.getParentCategoryId()!=null){
            productCategories.setParentCategoryId(productCategories.getId());
        }
        save(productCategories);
    }

    /**
     * 修改商品分类
     *
     * @param productCategories 商品分类
     * @return 结果
     */
    @Override
    public int updateProductCategories(ProductCategories productCategories)
    {
        return productCategoriesMapper.updateProductCategories(productCategories);
    }

    /**
     * 批量删除商品分类
     *
     * @param ids 需要删除的商品分类主键
     * @return 结果
     */
    @Override
    public int deleteProductCategoriesByIds(Integer[] ids)
    {
        return productCategoriesMapper.deleteProductCategoriesByIds(ids);
    }

    /**
     * 删除商品分类信息
     *
     * @param id 商品分类主键
     * @return 结果
     */
    @Override
    public int deleteProductCategoriesById(Integer id)
    {
        return productCategoriesMapper.deleteProductCategoriesById(id);
    }

    /**
     * 两级联动商品分类
     *
     * @param
     * @return
     */
    @Override
    public List<ProductCategories> getList() {
        return productCategoriesMapper.getList();
    }

    @Override
    public CategoryProductPageVO getCategoryTreeWithInitialProducts() {
        // 1. 查询所有显示的分类，并按权重排序
        List<ProductCategories> allCategories = this.list(
                new QueryWrapper<ProductCategories>().eq("is_displayed", 1).orderByAsc("sort_order")
        );

        // 2. 在内存中将列表组装成树形结构
        List<ProductCategories> categoryTree = allCategories.stream()
                .filter(category -> category.getParentCategoryId() == null || category.getParentCategoryId() == 0) // 筛选出一级分类
                .map(category -> {
                    category.setChildren(getChildren(category, allCategories)); // 为一级分类设置子分类
                    return category;
                })
                .collect(Collectors.toList());

        // 3. 获取默认的商品列表
        List<ProductGoods> initialProductList = new ArrayList<>();
        if (!categoryTree.isEmpty() && categoryTree.get(0).getChildren() != null && !categoryTree.get(0).getChildren().isEmpty()) {
            // 找到第一个一级分类下的第一个二级分类作为默认
            Integer defaultCategoryId = categoryTree.get(0).getChildren().get(0).getId();
            initialProductList = this.selectProductGoodsListByCategoryId(defaultCategoryId);
        }

        // 4. 封装到VO对象中返回
        CategoryProductPageVO resultVO = new CategoryProductPageVO();
        resultVO.setCategoryTree(categoryTree);
        resultVO.setProductList(initialProductList);

        return resultVO;
    }

    @Override
    public List<ProductGoods> selectProductGoodsListByCategoryId(Integer categoryId) {
        return productCategoriesMapper.selectProductGoodsListByCategoryId(categoryId);
    }

    @Override
    public List<ProductCategoriesDto> getCategoryTree() {
        List<ProductCategories> list= productCategoriesMapper.findAll();
        return  buildTree(list, null);
    }
    private List<ProductCategoriesDto> buildTree(List<ProductCategories> list, Long parentId) {

        List<ProductCategoriesDto> ProductCategoriesDtoArrayList = new ArrayList<>();
        for (ProductCategories cat : list) {
            if (Objects.equals(cat.getParentCategoryId(), parentId)) {
                ProductCategoriesDto productCategoriesDto = new ProductCategoriesDto();
                productCategoriesDto.setValue(Long.valueOf(cat.getId()));
                productCategoriesDto.setLabel(cat.getCategoryName());
                productCategoriesDto.setChildren(buildTree(list, Long.valueOf(cat.getId())));
                ProductCategoriesDtoArrayList.add(productCategoriesDto);
            }
        }
        return ProductCategoriesDtoArrayList;
    }

    /**
     * 递归查找子分类的辅助方法
     */
    private List<ProductCategories> getChildren(ProductCategories root, List<ProductCategories> all) {
        return all.stream()
                .filter(category -> root.getId().equals(category.getParentCategoryId()))
                .map(category -> {
                    // 如果需要支持三级或更多级分类，可以在这里继续递归调用
                    // category.setChildren(getChildren(category, all));
                    return category;
                })
                .collect(Collectors.toList());
    }

}
